<template>
  <!-- 上传组件 -->
  <el-upload
    v-model="imgUrl"
    class="single-uploader"
    :show-file-list="false"
    :before-upload="handleBeforeUpload"
		:on-error="onError"
			:on-success="onSuccess"
    :http-request="uploadFile"
  >
	  <el-button type="primary">点击上传文件</el-button>
	  <template #tip>
		  <div class="el-upload__tip">

		  </div>
	  </template>

  </el-upload>
</template>

<script setup lang="ts">
import { UploadRawFile, UploadRequestOptions } from "element-plus";
import { uploadFileApi } from "@/api/file";
import { ElLoading } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue"]);
const imgUrl = useVModel(props, "modelValue", emit);
let loading = ref(undefined);
/**
 * 自定义上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  const { data: fileInfo } = await uploadFileApi(options.file);
  imgUrl.value =  fileInfo.url;
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
	loading = ElLoading.service({
		lock: true,
		text: '资源正在上传中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
  // if (file.size > 2 * 1048 * 1048) {
  //   ElMessage.warning("上传图片不能大于2M");
  //   return false;
  // }
  return true;
}
function onError(){
	loading.close();
	ElMessage.error('上传失败')
}
function onSuccess(){
	loading.close();
	ElMessage({
		message: '上传成功',
		type: 'success',
	})
}
</script>

<style scoped>
.single-uploader .single {
  display: block;
  width: 178px;
  height: 178px;
}
</style>

<style>
.single-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.single-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.single-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
